//
//  imageToolPlugIn.m
//  imageTool
//

#import "imageToolPlugIn.h"


@implementation imageToolPlugIn

-(BOOL)plugInLoaded
{
    return YES;
}

+(int)imageAverage:(NSImage *)srcImage
{
    NSBitmapImageRep *srcImageRep = [NSBitmapImageRep
                    imageRepWithData:[srcImage TIFFRepresentation]];
    
    int w = [srcImageRep pixelsWide];
    int h = [srcImageRep pixelsHigh];
    int area = w*h;
    
    unsigned char *srcData = [srcImageRep bitmapData];
    // srcData is the straight-up bitmap data of the image
    // it's the BINARY representation of said data
    unsigned char *p1;
    int colorTotal = 0;
    
    int n = [srcImageRep bitsPerPixel] / 8;
    
    int x, y;
    for ( y = 0; y < h; y++ ) {
        for ( x = 0; x < w; x++ ) {
            p1 = srcData + n * (y * w + x);       
            colorTotal += (int)rint((*p1 + *(p1 + 1) + *(p1 + 2)) / 3);
        }
    }
    int colorAverage = colorTotal / area;
    return colorAverage;
}

@end
